package com.example.zero.Activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.zero.R;
import com.example.zero.Utils.ApplicationUtil;
import com.example.zero.Utils.HttpUtils;
import com.example.zero.Utils.SharedPreUtil;
import com.example.zero.Utils.ToastUtil;
import com.example.zero.Utils.UrlConstants;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;
import org.json.JSONObject;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SubscribeActivity extends AppCompatActivity {

    @BindView(R.id.flowlayout)
    TagFlowLayout flowlayout;
    @BindView(R.id.tv_selected)
    TextView tvSelected;
    @BindView(R.id.flowlayout_selected)
    TagFlowLayout flowlayoutSelected;
    private Context context;
    private String[] mVals = new String[]
            {"Java", "Android", "IOS", "AI", "BigData", "BlockChain",
                    "CloudCompute", "Microservice", "Angular", " Python", " ReactNative",
                    " Hadoop", " Redis", " SpringBoot/Spring Cloud ", " Vue.js"};
    private int maxSelected = 5;
    private Set<Integer> selectedList;
    private String[] mValsSelected;
    private TitleBar mTitleBar;
    private Button subscribe_submit;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_subscribe);
        ButterKnife.bind(this);
        context = this;

        subscribe_submit = (Button) findViewById(R.id.subscribe_submit);
        subscribe_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectedList = flowlayout.getSelectedList();
                String str = "";
                for (Integer index:selectedList){
                    str+=index;
                    str+=",";
                }
                final String subsTypes = str;
                Log.d("selectedList",selectedList.size()+"");

                if (!HttpUtils.isNetworkAvalible(getBaseContext())) {
                    Toast.makeText(getBaseContext(),"Can not connect to server， please check network configuration!", Toast.LENGTH_SHORT).show();
                } else {
                    String username = (String) SharedPreUtil.getParam(getBaseContext(), SharedPreUtil.LOGIN_DATA, "");
                    Map<String,String> map = new HashMap<String,String>();
                    map.put("subTypes",subsTypes);
                    map.put("loginId",username);
                    Callback callback = new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e("setOnClickListener",e.getMessage());
                            ToastUtil.makeText(SubscribeActivity.this,"Submit failure, please try again!");
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            Log.e("response","response: "+response);
                            try {
                                if (response.isSuccessful()){
                                    Log.e("setOnClickListener","response isSuccessful");
                                    JSONObject jsonObject = new JSONObject(response.body().string());
                                    String resultCode = jsonObject.getString("resultCode");
                                    if ("00200000".equals(resultCode)){
                                        SharedPreUtil.setParam(SubscribeActivity.this, SharedPreUtil.USER_DATA_SUB, subsTypes);
                                        Intent intent = new Intent(SubscribeActivity.this, MainActivity.class);
                                        startActivity(intent);
                                        finish();
                                    }else {
                                        Toast.makeText(SubscribeActivity.this, "Submit failure, please try again!", Toast.LENGTH_SHORT).show();
                                    }
                                }else {
                                    Toast.makeText(SubscribeActivity.this, "Submit failure, please try again!", Toast.LENGTH_SHORT).show();
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    };
                    HttpUtils.requestPostHttp(UrlConstants.SUBSCRIBE_API,map,callback);
                }
            }
        });
        initFlowLayout();
        initFlowLayoutSelected();
        initTitleBar();
        ApplicationUtil.getInstance().addActivity(this);
    }

    /**
     * 初始化所有标签的FlowLayout
     */
    private void initFlowLayout() {
        TagAdapter tagAdapter = new TagAdapter(mVals) {
            @Override
            public View getView(FlowLayout parent, int position, Object o) {

                TextView view = (TextView) View.inflate(context, R.layout.flowlayout_textview_selected, null);
                view.setText(mVals[position]);
                return view;
            }
        };
        //预先设置选中
        String subscribe = (String) SharedPreUtil.getParam(getBaseContext(), SharedPreUtil.USER_DATA_SUB, "");
        Log.d("subscribe=========>>>",subscribe+"2");
        if (!TextUtils.isEmpty(subscribe)&&!"null".equals(subscribe)){
            String[] arrStr = subscribe.split(",");
            Log.d("arrStr length",arrStr.length+"");
            if (arrStr!=null&&arrStr.length>0){
                int[] arrInt = new int[arrStr.length];
                for (int i = 0; i < arrStr.length; i++) {
                    // tagAdapter.setSelected(Integer.parseInt(arrStr[i]),i);
                    arrInt[i] = Integer.parseInt(arrStr[i]);
                    Log.d("arrInt"+i,arrInt[i]+"");
                }
                Log.d("arrInt",arrInt.length+"");
                tagAdapter.setSelectedList(arrInt);
            }
        }



        flowlayout.setAdapter(tagAdapter);

        //设置最大选中数
        flowlayout.setMaxSelectCount(maxSelected);

        //为FlowLayout的标签设置监听事件
        flowlayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                if (selectedList.size() >= maxSelected) {
                    ToastUtil.makeText(context, "The maximum number has been reached" + maxSelected);
                } else {
                    ToastUtil.makeText(context, mVals[position]);
                }
                return true;
            }
        });

        //为FlowLayout的标签设置选中监听事件
        flowlayout.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
            @Override
            public void onSelected(Set<Integer> selectPosSet) {
                initFlowLayoutSelected();
            }
        });
    }

    /**
     * 初始化选中标签的FlowLayout
     */
    private void initFlowLayoutSelected() {
        int i = 0;
        //获得所有选中的position集合,例如[1,2,3,4]
        selectedList = flowlayout.getSelectedList();
        mValsSelected = new String[selectedList.size()];
        Iterator<Integer> iterator = selectedList.iterator();
        while (iterator.hasNext()) {
            mValsSelected[i] = mVals[iterator.next()];
            i++;
        }
        tvSelected.setText("Maximum number of choices：" + maxSelected + "（selected" + selectedList.size() + ")");
        flowlayoutSelected.setAdapter(new TagAdapter(mValsSelected) {
            @Override
            public View getView(FlowLayout parent, int position, Object o) {

                TextView view = (TextView) View.inflate(context, R.layout.flowlayout_textview_no_selected, null);
                view.setText(mValsSelected[position]);
                return view;
            }
        });
    }

    private void initTitleBar(){
        mTitleBar = (TitleBar) findViewById(R.id.tb_main_title_bar);
        mTitleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }
        });
    }
}
